﻿@using Huirui.Cavan.Domain.MainBoundedContext.SalesModule
@model Huirui.Cavan.Presentation.ViewModel.SalesModule.ISalesReturnViewModel
@{
    Layout = null;
}
@using (Html.BeginForm(ActionConst.ADD, ControllerConst.SALESRETURN))
{
    <div class="tool_bar">
        <input id="salesreturn_save" type="submit" style="display: none;" />
        <input id="salereturn_reset" type="reset" style="display: none" />
        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-save'"
            onclick="javascript:$('#salesreturn_save').click()">保存</a>
        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-add'">新增</a>
        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-copy',disabled:true">复制</a>
        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-delete'">删除</a>
        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-undo'"
            onclick="javascript:$('#salereturn_reset').click()">重置</a>
        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-building'" onclick="openWindow('selectStockWindowFromSales')">按销售退货</a>
        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-search'">查询</a>
        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-print'">打印</a>
        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-collapse'"
            onclick="toggleHeard()">折叠/展开</a>
    </div>
    <div class="customer_div">
        <label>
        </label>

        <label>
        </label>

    </div>
    <table class="form_heard">
        <tr>
            <td class="c100">
                <label>
                    退货日期:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.ReturnDate, new { id = "returnDate" })
            </td>
            <td class="c100">
                <label>
                    出库单号:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.Id, new { id = "id" })
            </td>
        </tr>
        <tr>
            <td class="c100">
                <label>
                    客户*:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.Customer.Id, new { id = "customerCodeForSalesReturn" })
            </td>
            <td colspan="2">
                @Html.TextBoxFor(m => m.Item.Customer.Name, new { id = "customerNameForSalesReturn" })
            </td>
            <td class="c100">
                <label>
                    销售人员:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.SaleEmployee.Id, new { id = "saleEmployeeCodeForSalesReturn" })
            </td>
            <td class="c100">
                <label>
                    接单仓库:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.WareHouse.Id, new { id = "wareHouseAddressForSalesReturn" })
            </td>
        </tr>
        <tr>
            <td class="c100">
                <label>
                    币别:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.Currency, new { id = "currency" })
            </td>
            <td class="c100">
                <label>
                    汇率:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.CurrencyRate, new { id = "currencyRate" })
            </td>
            <td class="c100">
                <label>
                    税率:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.TaxRate, new { id = "taxRate" })
            </td>
        </tr>
        <tr>
            <td class="c100">
                <label>
                    送货地址:</label>
            </td>
            <td colspan="4">
                @Html.TextBoxFor(m => m.Item.DeliveryAddress, new { id = "deliveryAddress" })
            </td>
            <td class="c160">
                <a>请选择常用送货地址</a>
            </td>
            <td class="c100">
                <a>送货单号:</a>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.DeliveryCode, new { id = "deliveryCode" })
            </td>
        </tr>
        <tr>
            <td class="c100">
                <a>备注:</a>
            </td>
            <td colspan="4">
                @Html.TextAreaFor(m => m.Item.Remark, new { id = "remark", cols = "80", rows = "2" })
                <a>请选择常用备注</a>
            </td>
        </tr>
    </table>
   
    @Html.HiddenFor(m => m.StockInOutDetails, new { id = "stockInOutDetails" })
    @Html.HiddenFor(m => m.Sales, new { id = "sales" })
}

<table id="selectedStocksForSalesReturn" title="存货列表" toolbar="#sale_return_tb">
</table>
<div id="sale_return_tb">
    <a href="#" id="selectStockForSalesReturn" class="easyui-linkbutton" iconcls="icon-checked"
        plain="true" onclick="InitSelectStock('stocksForSalesReturn');openWindow('selectStockWindowForSalesReturn')">选择商品</a>
</div>
@{ Html.RenderAction(ActionConst.SEARCH, ControllerConst.STOCK, new { purpose = "ForSalesReturn" }); }
@{ Html.RenderAction(ActionConst.SEARCH, ControllerConst.CUSTOMER, new { purpose = "ForSalesReturn" }); }
@{ Html.RenderAction(ActionConst.SEARCH, ControllerConst.WAREHOUSE, new { purpose = "ForSalesReturn" }); }
@{ Html.RenderAction(ActionConst.SEARCH, ControllerConst.EMPLOYEE, new { purpose = "ForSalesReturn" }); }
@{ Html.RenderAction(ActionConst.STOCKSFROMSALES, ControllerConst.STOCK); }

<script type="text/javascript">
    $(function () {
        var lastIndex;
        var salesDetails;
        $('#selectedStocksForSalesReturn').datagrid({
            columns: [[
                { field: 'NoPrefixId', title: '存货编码', width: 100 },
                { field: 'Id', title: '存货编码', width: 100 },
                { field: 'Name', title: '存货名称', width: 80 },
                { field: 'Specification', title: '规格', width: 60 },
                { field: 'UnitTransfer', title: '计量单位', width: 100 },
                { field: 'Number', title: '数量', width: 100, editor: { type: 'text' } },
                { field: 'AssistantNumber', title: '辅助数量', width: 100 },
                { field: 'StandardSalesPrice', title: '单价', width: 100 },
                { field: 'DiscountRate', title: '折扣率', width: 100 },
                { field: 'DiscountAmount', title: '折扣额', width: 80 },
                { field: 'SalesAmount', title: '销售额', width: 80 },
                { field: 'LocalCurrencySalesAmount', title: '本币销售额', width: 80 },
                { field: 'TaxAmount', title: '税额', width: 80 },
                { field: 'UnTaxAmount', title: '未税销售额', width: 80 },
                { field: 'SalesCost', title: '销售成本', width: 80 },
                { field: 'SalesOrderCode', title: '销售订单号', width: 80 },
                { field: 'Remark', title: '备注', width: 80 }
            ]]
        });

        $("#searchStockForSalesReturn").submit(function () {
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    if (result.total > 0) {
                        $('#stocksForSalesReturn').datagrid({
                            data: result,
                            checkOnSelect: true,
                            selectOnCheck: true
                        });
                    }
                },
                error: function () {
                    alert('系统繁忙，请稍候再试');
                }
            })

            return false;
        });

        $("#doSelectStockForSalesReturn").bind("click", function () {
            $('#selectedStocksForSalesReturn').datagrid('loadData', { total: 0, rows: [] });
            var rows = $('#stocksForSalesReturn').datagrid('getSelections');
            for (var i = 0; i < rows.length; i++) {
                insert(rows[i].NoPrefixId, rows[i].Id, rows[i].Name, rows[i].Specification, rows[i].UnitTransfer, 0, 0, rows[i].StandardSalesPrice, rows[i].DiscountRate, 0, 0, 0, 0, 0, 0, $("#salesOrderCode").val(), 'test');
            }
            closeWindow('selectStockWindowForSalesReturn')
        });

        $("#doSelectStocksFromSales").bind("click", function () {
            $('#selectedStocksForSalesReturn').datagrid('loadData', { total: 0, rows: [] });
            var rows = $('#stocksFromSalesOrder').datagrid('getSelections');
            for (var i = 0; i < rows.length; i++) {
                $('#stocksFromSalesOrder').datagrid('endEdit', i);
                insert(rows[i].NoPrefixId, rows[i].Code, rows[i].Name, rows[i].Specification, rows[i].UnitTransfer, rows[i].CurrentStockOutNumber, 0, rows[i].CurrentStockOutPrice, rows[i].DiscountRate, 0, 0, 0, 0, 0, 0, $("#salesOrderCode").val(), 'test');
            }
            closeWindow('selectStockWindowFromSales')
        });

        function insert(noPrefixId, id, name, specification, unitTransfer, number, assistantNumber, standardSalesPrice, discountRate, discountAmount, salesAmount, localCurrencySalesAmount, taxAmount, unTaxAmount, salesCost, salesOrderCode, remark) {
            var rows = $('#selectedStocksForSalesReturn').datagrid('getRows');
            index = -1;
            if (rows.length == 0) {
                index = 0;
            }
            else {
                index = rows.length;
            }

            $('#selectedStocksForSalesReturn').datagrid('insertRow', {
                index: index,
                row: {
                    NoPrefixId: noPrefixId,
                    Id: id,
                    Name: name,
                    Specification: specification,
                    UnitTransfer: unitTransfer,
                    Number: number,
                    AssistantNumber: assistantNumber,
                    StandardSalesPrice: standardSalesPrice,
                    DiscountRate: discountRate,
                    DiscountAmount: discountAmount,
                    SalesAmount: salesAmount,
                    LocalCurrencySalesAmount: localCurrencySalesAmount,
                    TaxAmount: taxAmount,
                    UnTaxAmount: unTaxAmount,
                    SalesCost: salesCost,
                    SalesOrderCode: salesOrderCode,
                    Remark: remark
                }
            });
            $('#selectedStocksForSalesReturn').datagrid('selectRow', index);
            $('#selectedStocksForSalesReturn').datagrid('beginEdit', index);

            var ed = $('#selectedStocksForSalesReturn').datagrid('getEditors', index);
            for (var i = 0; i < ed.length; i++) {
                var e = ed[i];
                if (e.field == "Number") {
                    $(e.target).attr("selectedStockRowIndex", index);
                    $(e.target).bind("click", function () {
                        $('#selectedStocksForSalesReturn').datagrid('selectRow', $(this).attr("selectedStockRowIndex"));
                    });
                    $(e.target).bind("blur", function () {
                        var number = $(this).val();
                        var currentIndex = $(this).attr("selectedStockRowIndex");
                        var currentRow = $('#selectedStocksForSalesReturn').datagrid('getSelected');
                        var taxRate = $("#taxRate").val() != '' ? $("#taxRate").val() : 0;
                        var rowId = $(this).parents().filter("tr").filter("[datagrid-row-index=" + currentIndex + "]").attr("id");
                        $("#" + rowId).find("td").each(function () {
                            if ($(this).attr("field") == "SalesAmount") {
                                $(this).find("div").html(number * currentRow.StandardSalesPrice * (1 - currentRow.DiscountRate / 100));
                            }
                            if ($(this).attr("field") == "DiscountAmount") {
                                $(this).find("div").html(number * currentRow.StandardSalesPrice * (currentRow.DiscountRate / 100));
                            }
                            if ($(this).attr("field") == "TaxAmount") {
                                $(this).find("div").html((number * currentRow.StandardSalesPrice) * (1 - (100 / ($("#taxRate").val() + 100))));
                            }
                            if ($(this).attr("field") == "UnTaxAmount") {
                                $(this).find("div").html((number * currentRow.StandardSalesPrice * (1 - currentRow.DiscountRate / 100)) - (number * currentRow.StandardSalesPrice) * (1 - (100 / ($("#taxRate").val() + 100))));
                            }
                        });
                        $('#selectedStocksForSalesReturn').datagrid('unselectRow', currentIndex);
                        currentRow.Number = number;

                        $.ajax({
                            url: '/stock/cbso?id=' + currentRow.Id + '&number=' + number,
                            type: 'Post',
                            success: function (data) {
                                if (data) {
                                    $("#" + rowId).find("td").each(function () {
                                        if ($(this).attr("field") == "SalesCost") {
                                            $(this).find("div").html(data.SalesCost);
                                        }
                                    });
                                }
                            },
                            error: function () {
                                alert('系统繁忙，请稍候再试');
                            }
                        })
                    })
                }
            }
        }

        $("form[action^='/salesReturn/add']").submit(function () {
            var rows = $('#selectedStocksForSalesReturn').datagrid('getRows');
            stockInOutDetails = "[";
            for (var i = 0; i < rows.length; i++) {
                if (i == (rows.length - 1)) {
                    stockInOutDetails = stockInOutDetails + "{ \"Stock\" : { \"Id\" : \"" + rows[i].Id + "\"}, \"Number\" : " + rows[i].Number + ", \"Description\" : \"" + rows[i].SalseCode + "\" }";
                }
                else {
                    stockInOutDetails = stockInOutDetails + "{ \"Stock\" : { \"Id\" : \"" + rows[i].Id + "\"}, \"Number\" : " + rows[i].Number + ", \"Description\" : \"" + rows[i].SalseCode + "\" },";
                }
            }
            stockInOutDetails = stockInOutDetails + "]";
            $("#stockInOutDetails").val(stockInOutDetails);
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (data) {
                    if (data.IsSuccess) {
                        alert(data.Messages[0]);
                    }
                },
                error: function () {
                    alert('系统繁忙，请稍候再试');
                }
            })

            return false;
        });

        $("#searchStockFromSales").submit(function () {
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    if (result.total > 0) {
                        $('#stocksFromSales').datagrid({
                            columns: [[
                                { field: 'IsSelected', title: '选择', width: 60, checkbox: true },
                                { field: 'ReturnNumber', title: '退货数量', width: 100 },
                                { field: 'ReturnAmount', title: '退货金额', width: 80, align: 'center' },
                                { field: 'SalesDate', title: '销售日期', width: 60 },
                                { field: 'SalseCode', title: '销售编号', width: 60 },
                                { field: 'Name', title: '存货', width: 80, align: 'right' },
                                { field: 'Number', title: '数量', width: 80, align: 'right' },
                                { field: 'StandardSalesPrice', title: '单价', width: 80, align: 'right' },
                                { field: 'Amount', title: '金额', width: 80, align: 'right' }
                            ]],
                            data: result
                        });
                        $("#sales").val(result.Sales);
                        var sales = JSON.parse(result.Sales);
                        $("#employee").val(sales[0].SaleEmployeeCode);
                        $("#customer").val(sales[0].CustomerCode);
                        $("#currency").val(sales[0].Currency);
                        $("#currencyRate").val(sales[0].CurrencyRate);
                        $("#wareHouse").val(sales[0].WareHouseCode);
                        $("#deliveryAddress").val(sales[0].DeliveryAddress);
                        $("#taxRate").val(sales[0].TaxRate);
                        $("#remark").val(sales[0].Remark);

                        var rows = $('#stocksFromSales').datagrid('getRows');
                        for (var i = 0; i < rows.length; i++) {
                            $('#stocksFromSales').datagrid('beginEdit', i);
                        }
                    }
                    else {
                        $('#stocksFromSales').datagrid('loadData', { total: 0, rows: [] });
                    }
                },
                error: function () {
                    alert('系统繁忙，请稍候再试');
                }
            })

            return false;
        });

        $("#customerCodeForSalesReturn").bind("click", function () {
            InitSelectCustomer('customersForSalesReturn');
            openWindow("selectCustomerWindowForSalesReturn");
        });

        $("#searchCustomerForSalesReturn").submit(function () {
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    if (result.total > 0) {
                        $('#customersForSalesReturn').datagrid({
                            data: result,
                            checkOnSelect: true,
                            selectOnCheck: true
                        });
                    }
                },
                error: function () {
                    alert('系统繁忙，请稍候再试');
                }
            })

            return false;
        });

        $("#doSelectCustomerForSalesReturn").bind("click", function () {
            var currentRow = $('#customersForSalesReturn').datagrid('getSelected');
            $("#customerCodeForSalesReturn").val(currentRow.Id);
            $("#customerNameForSalesReturn").val(currentRow.Name);
            closeWindow("selectCustomerWindowForSalesReturn");
        });

        $("#wareHouseAddressForSalesReturn").bind("click", function () {
            InitSelectWareHouse('wareHousesForSalesReturn');
            openWindow("selectWareHouseWindowForSalesReturn");
        });

        $("#searchWareHouseForSalesReturn").submit(function () {
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    if (result.total > 0) {
                        $('#wareHousesForSalesReturn').datagrid({
                            data: result,
                            checkOnSelect: true,
                            selectOnCheck: true
                        });
                    }
                },
                error: function () {
                    alert('系统繁忙，请稍候再试');
                }
            })

            return false;
        });

        $("#doSelectWareHouseForSalesReturn").bind("click", function () {
            var currentRow = $('#wareHousesForSalesReturn').datagrid('getSelected');
            $("#wareHouseCodeForSalesReturn").val(currentRow.Id);
            $("#wareHouseAddressForSalesReturn").val(currentRow.Address);
            closeWindow("selectWareHouseWindowForSalesReturn");
        });

        $("#saleEmployeeCodeForSalesReturn").bind("click", function () {
            InitSelectEmployee('employeesForSalesReturn');
            openWindow("selectEmployeeWindowForSalesReturn");
        });

        $("#searchEmployeeForSalesReturn").submit(function () {
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    if (result.total > 0) {
                        $('#employeesForSalesReturn').datagrid({
                            data: result,
                            checkOnSelect: true,
                            selectOnCheck: true
                        });
                    }
                },
                error: function () {
                    alert('系统繁忙，请稍候再试');
                }
            })

            return false;
        });

        $("#doSelectEmployeeForSalesReturn").bind("click", function () {
            var currentRow = $('#employeesForSalesReturn').datagrid('getSelected');
            $("#saleEmployeeCodeForSalesReturn").val(currentRow.Id);
            $("#saleEmployeeNameForSalesReturn").val(currentRow.Name);
            closeWindow("selectEmployeeWindowForSalesReturn");
        });

    });
</script>
